package com.tuozixuan.jdk19;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class VirtualThreadDemo {

	public static void main(String[] args) throws InterruptedException {
		
		Runnable runnable = () -> {
		    System.out.println("Hello, www.didispace.com");
		};
		
		// 使用静态构建器方法
		Thread virtualThread = Thread.startVirtualThread(runnable);
		virtualThread.join();
		
		// 使用Thread.ofVirtual()来创建
		Thread virtualThread2 = Thread.ofVirtual().name("dispace-virtual-thread").start(runnable);
		virtualThread2.join();
		
		//  与ExecutorService结合使用
		try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
		    for (int i = 0; i < 2; i++) {
		        executorService.submit(runnable);
		    }
		}
		
		// 使用虚拟线程工厂
		ThreadFactory virtualThreadFactory = Thread.ofVirtual()
		        .name("didispace", 0)
		        .factory();

		Thread factoryThread = virtualThreadFactory.newThread(runnable);
		factoryThread.start();
		factoryThread.join();
		
	}

}
